import React from "react";
import ReactDOM from "react-dom/client";
import { Provider, connect, useSelector } from "react-redux";
import { legacy_createStore } from "redux";

export const ACTIONS = {
  INCREMENT: "INCREMENT",
};

export const incrementAction = (payload) => ({
  type: ACTIONS.INCREMENT,
  payload,
});

function todos(state = { counters: { counter: 0 } }, action) {
  switch (action.type) {
    case ACTIONS.INCREMENT:
      return {
        ...state,
        counters: { ...state.counters, counter: state.counters.counter + 1 },
      };
    default:
      return state;
  }
}

const countersSelector = (state) => {
  console.log("RUNNING SELECTOR", state.counters);
  return state.counters;
};

class ChildBase extends React.Component {
  componentDidMount() {
    if (this.props.counter < 3) {
      this.props.increment();
    }
  }

  componentDidUpdate() {
    if (this.props.counter < 3) {
      this.props.increment();
    }
  }

  render() {
    return <div>Child: {this.props.counter}</div>;
  }
}

const mapStateToProps = (state) => ({
  counter: state.counters.counter,
});

const mapDispatchToProps = (dispatch) => ({
  increment: () => dispatch(incrementAction()),
});

const Child = connect(mapStateToProps, mapDispatchToProps)(ChildBase);

function App(props) {
  console.log("App CALLING USESELECTOR");
  const counters = useSelector(countersSelector);
  console.log(counters);

  return (
    <div className="App">
      <div>App: {counters.counter}</div>
      <Child />
    </div>
  );
}

const store = legacy_createStore(todos, { counters: { counter: 0 } });
ReactDOM.createRoot(document.getElementById("root")).render(
  <Provider store={store}>
    <App />
  </Provider>
);
